package com.xiguaji.tiktok.task.aweme.repository;

import com.xiguaji.tiktok.task.aweme.Aweme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.List;

public class AwemeExtRepositoryImpl implements AwemeExtRepository {

    @Autowired
    @Lazy
    AwemeRepository awemeRepository;

    private void insertOrUpdateByCondition(Aweme aweme, boolean isSkipUpdate, String operator) {
        // lock here
        var optionalAweme = awemeRepository.findByoAwemeId(aweme.getOAwemeId());

        if (!optionalAweme.isPresent()) {
            aweme.setCreateBy(operator);
            aweme.setUpdateBy(operator);
            awemeRepository.save(aweme);
        } else if (optionalAweme.isPresent() && !isSkipUpdate) {
            var origin = optionalAweme.get();
            aweme.setId(origin.getId());
            aweme.setCreateTime(origin.getCreateTime());
            aweme.setCreateBy(origin.getCreateBy());
            aweme.setUpdateBy(operator);
            awemeRepository.save(aweme);
        }
    }

    @Override
    public void insertOrUpdate(Aweme aweme, String operator) {
        insertOrUpdateByCondition(aweme, false, operator);
    }

    @Override
    public void insertOrUpdate(List<Aweme> awemes, String operator) {
        awemes.forEach(aweme -> insertOrUpdate(aweme, operator));
    }

    @Override
    public void insertWhenNotExists(Aweme aweme, String operator) {
        insertOrUpdateByCondition(aweme, true, operator);
    }

    @Override
    public void insertWhenNotExists(List<Aweme> awemes, String operator) {
        awemes.forEach(aweme -> insertWhenNotExists(aweme, operator));
    }
}
